package com.tingfeng.xiuzhen.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tingfeng.xiuzhen.GlobalData;
import com.tingfeng.xiuzhen.MyApplication;
import com.tingfeng.xiuzhen.eventbus.MessageEvent;
import com.tingfeng.xiuzhen.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            boolean result = MyApplication.wxApi.handleIntent(getIntent(), this);
            if (!result) {
                Log.d(GlobalData.TAG, "参数不合法，未被SDK处理，退出");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyApplication.wxApi.handleIntent(data, this);
    }

    //
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        MyApplication.wxApi.handleIntent(intent, this);
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.d("wx_onReq", baseReq.toString());
    }

    @Override
    public void onResp(BaseResp baseResp) {
        String result = new Gson().toJson(baseResp);
        Log.d(GlobalData.TAG, "wx_onResp:" + result);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                //发送EventBus事件
                String code = ((SendAuth.Resp) baseResp).code;
                EventBus.getDefault().post(new MessageEvent(code));
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                // 取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                // 拒绝
                ToastUtils.showShortToast("取消微信登录");
                break;
            default:
                break;
        }
        finish();
    }
}
